<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>正课打印</title>
    <style>
        :root {
            --primary-color: #4CAF50;
            --primary-hover: #45a049;
            --border-color: #ddd;
            --bg-light: #f9f9f9;
            --bg-card: #fafafa;
            --text-primary: #333;
            --text-secondary: #666;
            --shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        * {
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: var(--text-primary);
            margin: 0;
            padding: 0;
            background-color: #fff;
        }

        .app {
            margin-top: 20px;
            max-width: 1200px;
            margin-left: auto;
            margin-right: auto;
            padding: 0 20px;
        }

        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 10px 0 20px;
            gap: 20px;
        }

        .view-toggle {
            display: flex;
            border: 1px solid var(--primary-color);
            border-radius: 4px;
            overflow: hidden;
        }

        .btn {
            padding: 8px 16px;
            background-color: white;
            color: var(--primary-color);
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .btn-toggle {
            border-right: 1px solid var(--primary-color);
        }

        .btn-toggle:last-child {
            border-right: none;
        }

        .btn-toggle.active {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-toggle:hover:not(.active) {
            background-color: #f0fff0;
        }

        .btn-toggle.active:hover {
            background-color: var(--primary-hover);
        }

        .btn-print {
            background-color: var(--primary-color);
            color: white;
            border: 1px solid var(--primary-color);
            border-radius: 4px;
            padding: 8px 16px;
            cursor: pointer;
            white-space: nowrap;
            font-weight: 500;
        }

        .btn-print:hover {
            background-color: var(--primary-hover);
        }

        .info-panel {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
            padding: 15px;
            background-color: var(--bg-light);
            border-radius: 4px;
            font-size: 14px;
            gap: 20px;
        }

        .section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px dashed #ccc;
        }

        .section:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }

        .section-title {
            text-align: center;
            margin: 20px 0;
            color: var(--text-primary);
            font-size: 18px;
            font-weight: bold;
        }

        .table-container {
            width: 100%;
            margin: 20px auto;
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            box-shadow: var(--shadow);
            min-width: 600px;
        }

        .data-table th,
        .data-table td {
            border: 1px solid var(--border-color);
            padding: 12px;
            text-align: left;
        }

        .data-table th {
            background-color: #f2f2f2;
            text-align: center;
            font-weight: bold;
        }

        .vocab-container {
            width: 100%;
            margin: 20px auto;
            text-align: center;
        }

        .vocab-title {
            margin: 20px 0;
            color: var(--text-primary);
            font-size: 20px;
        }

        .vocab-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .vocab-card {
            border: 1px solid var(--border-color);
            padding: 15px;
            border-radius: 4px;
            background-color: var(--bg-card);
            box-shadow: var(--shadow);
        }

        .vocab-card p {
            margin: 8px 0;
            font-size: 16px;
        }

        .loading-container {
            text-align: center;
            padding: 40px 20px;
        }

        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid var(--primary-color);
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        .error-message {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #f44336;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            z-index: 1000;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        @media (max-width: 768px) {
            .app {
                padding: 0 10px;
            }

            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .view-toggle {
                align-self: center;
            }

            .info-panel {
                flex-direction: column;
                gap: 10px;
            }

            .vocab-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 10px;
            }

            .section-title {
                font-size: 16px;
            }

            .data-table {
                min-width: 500px;
            }
        }

        @media print {
            /* 隐藏控制元素 */
            .controls {
                display: none;
            }

            /* 重置边距 */
            .app {
                margin-top: 0;
                padding: 0;
                max-width: 100%;
            }

            /* 确保打印内容完整显示 */
            body {
                background-color: white;
                padding: 0;
                margin: 0;
            }

            .section {
                page-break-inside: avoid;
            }

            .data-table {
                box-shadow: none;
            }
        }
    </style>
</head>
<body>
<div id="app" class="app">

    <div v-if="loading" class="loading-container">
        <div class="spinner"></div>
        <p>数据加载中...</p>
    </div>

    <div v-else-if="error" class="loading-container">
        <p>{{ error }}</p>
        <button class="btn btn-print" @click="retryLoad">重新加载</button>
    </div>
    <template v-else>
        <div class="controls">
            <div class="view-toggle">
                <button class="btn btn-toggle" :class="{ active: currentView === 'diglossia' }"
                        @click="setView('diglossia')">显示中英文
                </button>
                <button class="btn btn-toggle" :class="{ active: currentView === 'english' }"
                        @click="setView('english')">
                    显示英文
                </button>
                <button class="btn btn-toggle" :class="{ active: currentView === 'chinese' }"
                        @click="setView('chinese')">
                    显示中文
                </button>
            </div>
            <button class="btn btn-print" @click="handlePrint">确认打印</button>
        </div>
        <div class="info-panel">
            <div>授课句子总数：{{ sentenceCount }}</div>
            <div>学员：{{ recordInfo?.studentInfo?.name || '-' }} 授课老师：{{ recordInfo?.trainerInfo?.name || '-' }}
                授课时间：{{ formatDate(recordInfo?.actualStartTime) || '-' }}
            </div>
        </div>

        <template v-if="list && list.length > 0">
            <div v-for="(item, index) in list" :key="index" class="section">
                <h3 class="section-title">
                    {{ getSectionTitle(item) }}
                </h3>
                <div class="table-container">
                    <table class="data-table">
                        <tr v-for="(value, subIndex) in item.questionAnswerRecordList" :key="subIndex">
                            <th>{{ value?.parentId == 0 ? '母句' : '子句' }}</th>
                            <td class="en" :style="{ visibility: sentenceEn ? 'visible' : 'hidden' }">
                                <span v-if="sentenceEn" v-html="getSentenceEnWithColor(value, item,subIndex)"></span>
                                <span v-else>{{ value?.sentenceEn || '' }}</span>
                            </td>
                            <td class="cn" :style="{ visibility: sentenceZh ? 'visible' : 'hidden' }">
                                <span v-if="sentenceZh" v-html="getSentenceZhWithColor(value, item,subIndex)"></span>
                                <span v-else>{{ value?.sentenceZh || '' }}</span>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </template>

        <template v-if="coreVocabularyList && coreVocabularyList.length > 0">
            <div class="vocab-container">
                <h3 class="vocab-title">核心词汇</h3>
                <div class="vocab-grid">
                    <div class="vocab-card" v-for="(item, index) in coreVocabularyList" :key="index">
                        <p :style="{ visibility: sentenceEn ? 'visible' : 'hidden' }">{{ item.wordEn || '' }}</p>
                        <p :style="{ visibility: sentenceZh ? 'visible' : 'hidden' }">{{ item.wordZh || '' }}</p>
                    </div>
                </div>
            </div>
        </template>
    </template>
</div>

<script src="/vue/vue.min.js"></script>
<script src="/vue/axios.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            sentenceEn: true,
            sentenceZh: true,
            list: [],
            recordInfo: {},
            sentenceCount: 0,
            coreVocabularyList: [],
            currentView: 'diglossia',
            loading: true,
            error: null
        },
        methods: {
            async getRecordInfo() {
                try {
                    this.loading = true;
                    this.error = null;

                    // 获取URL参数
                    const urlParams = new URLSearchParams(window.location.search);
                    const recordId = urlParams.get('recordId');

                    if (!recordId) {
                        throw new Error('缺少recordId参数');
                    }

                    const response = await axios.post('/common_api/print/sentenceQuestionPrint', {
                        recordId: recordId
                    }, {
                        headers: {
                            'Server': 1,
                            'platform': 'common'
                        }
                    });

                    if (response.data.code === 0) {
                        const data = response.data.data || {};
                        this.list = data.list || [];
                        this.recordInfo = data.recordInfo || {};
                        this.sentenceCount = data.sentenceCount || 0;
                        this.coreVocabularyList = data.coreVocabularyList || [];
                    } else {
                        throw new Error(response.data.msg || '接口返回错误');
                    }
                } catch (error) {
                    console.error('获取记录信息失败:', error.message);
                    this.error = '数据加载失败: ' + error.message;
                } finally {
                    this.loading = false;
                }
            },

            setView(view) {
                this.currentView = view;
                switch (view) {
                    case 'diglossia':
                        this.sentenceEn = true;
                        this.sentenceZh = true;
                        break;
                    case 'english':
                        this.sentenceEn = true;
                        this.sentenceZh = false;
                        break;
                    case 'chinese':
                        this.sentenceEn = false;
                        this.sentenceZh = true;
                        break;
                }
            },

            handlePrint() {
                window.print();
            },

            retryLoad() {
                this.getRecordInfo();
            },

            formatDate(dateString) {
                if (!dateString) return '-';
                const date = new Date(dateString);
                return isNaN(date.getTime()) ? '-' : date.toLocaleString('zh-CN');
            },

            getSectionTitle(item) {
                if (!item) return '';
                const category = item.sayTeachSentenceInfo?.gradeInfo?.categoryInfo?.name || '';
                const grade = item.sayTeachSentenceInfo?.gradeInfo?.name || '';
                const name = item.sayTeachSentenceInfo?.name || '';
                return [category, grade, name].filter(Boolean).join('-');
            },
            processSentenceWithColors(sentence, wordColorList, isEnglish = true) {
                if (!sentence || !wordColorList || wordColorList.length === 0) {
                    return sentence;
                }

                let coloredSentence = sentence;

                // 按单词长度降序排列，避免短单词先被替换影响长单词
                const sortedWords = [...wordColorList].sort((a, b) =>
                    (b.wordEn || b.wordZh).length - (a.wordEn || a.wordZh).length
                );

                sortedWords.forEach(item => {
                    const word = isEnglish ? item.wordEn : item.wordZh;
                    const color = item.color;

                    if (word && color) {
                        // 使用正则表达式匹配单词，考虑单词边界
                        // const regex = new RegExp('(' + word + ')',  'i');
                        const regex = new RegExp(`(${this.escapeRegExp(word)})`, 'i');
                        coloredSentence = coloredSentence.replace(regex,
                            `<span style="color: ${color}">$1</span>`);
                    }
                });

                return coloredSentence;
            },

            escapeRegExp(string) {
                return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            },

            getSentenceEnWithColor(value, item,index) {
                if (!this.sentenceEn) return value?.sentenceEn || '';
                return this.processSentenceWithColors(
                    value?.sentenceEn,
                    item?.questionAnswerRecordList?.[index]?.sentenceWordColorList,
                    true
                );
            },

            getSentenceZhWithColor(value, item,index) {
                if (!this.sentenceZh) return value?.sentenceZh || '';
                return this.processSentenceWithColors(
                    value?.sentenceZh,
                    item?.questionAnswerRecordList?.[index]?.sentenceWordColorList,
                    false
                );
            }
        },
        created() {
            this.getRecordInfo();
        }
    });
</script>
</body>
</html>
